﻿define('ui/markerList/pointML', 
	['ui/controller/conditionController',
	 'ui/gis', 'ui/card/pointDetailCard'], 
	function(conditionController, gis, pointDetailCard) {

	/**
	 * 排口MarkerList，包含以下功能：
	 * 1、左侧面板：排口列表元素自定义渲染：编号、名称、企业、地址、行业、排污类型（废气废水）
	 * 2、分页初始化、销毁
	 * 3、地图排口点位信息：自定义点位信息；选择排口打开窗口查看排口信息
	 * 4、地图输入框输入编号或者名称后检索排口(条件包含区域、行业、监管类型、排污类型)，展示企业左侧面板与点位
	 * 5、包含的数据：
	 * 1）排口的点位数据列表，查看goPage方法请求的后台JSON数据
	 * 2）markerList属性，加载的MarkerList对象
	 * 3）inited，分页首次加载标记，false则首次调用initPagination从第一页开始渲染
	 */
	var pointML = {
		
		$keywords: $('#sole-input'),	
			
		markerList : null,	
		
		//分页初始化
		inited: false,
		
		//分页
	    $pagination: $('#pagination-enterprise'),
		
		//初始化分页器
		initPagination: function(page, totalPages){
			pointML.$pagination.twbsPagination({
	            totalPages: totalPages,
	            startPage: page,
	            prev: null,
	            first: '首页',
	            next: '下一页',
	            last: null,
	            initiateStartPageClick: false,
	            onPageClick: function(event, page) {
	            	pointML.goPage(page);
	            }
	        });
		},
		
		/**
		 * goPage方法为加载后台JSON数据的入口，获取数据后会重新渲染MarkerList
		 */
		goPage: function(page) {
	    	var keywords = pointML.$keywords.val();
	    	keywords = keywords=='排污许可企业'?'':keywords;
	    	var areacode = conditionController.getAreaCode();
	    	var codeTrade = conditionController.getTradeCode();
	    	var pointType = conditionController.getPointTypeCode();
	    	//console.log(adFormData);
	        ajaxProcess({
	            url : '/pls/gis/point/bycondition',
	            requestType : 'POST',
	            data : {
	            	page: page, 
	            	rows:30, 
	            	pointCode: keywords, 
	            	areacode: areacode,
	            	codeTrade:codeTrade,
	            	pointType:pointType
	            },
	            successHandle : function(data) {
	            	//console.log(data);
	            	pointML.renderTotal(data.data.pointquantity);
	            	pointML.markerList.render(data.data.listPoint);
	                
	                if (!pointML.inited) {
	                	pointML.inited = true;
	                    //首次初始化
	                    if(page<=data.data.pages) {
	                    	pointML.initPagination(page, data.data.pages);
	                    }
	                }
	            }
	        });
	    },
		
	    /**
	     * load方法应该在初次加载MarkerList时调用,无论如何别多次调用，重新渲染请使用reRenderData
	     */
		load: function(){
			pointML.clearData();
			AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],
			    function(MarkerList, SimpleMarker, SimpleInfoWindow) {

			    //即jQuery/Zepto
			    var $ = MarkerList.utils.$;

			    var defaultIconStyle = 'red', //默认的图标样式
			        hoverIconStyle = 'green', //鼠标hover时的样式
			        selectedIconStyle = 'purple' //选中时的图标样式
			    ;

			    var markerList = new MarkerList({
			        map: gis.map,
			        //ListElement对应的父节点或者ID
			        listContainer: "enterpriseList", //document.getElementById("myList"),
			        //选中后显示

			        //从数据中读取位置, 返回lngLat
			        getPosition: function(item) {
			            return [item.longitude, item.latitude];
			        	//return item.location;
			        },
			        //数据ID，如果不提供，默认使用数组索引，即index
			        getDataId: function(item, index) {

			            return item.id;
			        },
			        getInfoWindow: function(data, context, recycledInfoWindow) {
			        	//console.log("窗体"+data);
			        	var div = '<div>'+
			        				'<p>编号：'+data.pointcode+'</p>'+
			        				'<p>企业：'+data.entername+'</p>'+
			        			  '</div>';
			            if (recycledInfoWindow) {

			                recycledInfoWindow.setInfoTitle(data.pointname);
			                recycledInfoWindow.setInfoBody(div);

			                return recycledInfoWindow;
			            }

			            return new SimpleInfoWindow({
			                infoTitle: data.pointname,
			                infoBody: div,
			                offset: new AMap.Pixel(0, -37)
			            });
			        },
			        //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
			        getMarker: function(data, context, recycledMarker) {

			            var label = context.index+1;//String.fromCharCode('A'.charCodeAt(0) + context.index);

			            if (recycledMarker) {
			                recycledMarker.setIconLabel(label);
			                return;
			            }

			            return new SimpleMarker({
			                containerClassNames: 'my-marker',
			                iconStyle: defaultIconStyle,
			                iconLabel: label
			            });
			        },
			        //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
			        getListElement: function(data, context, recycledListElement) {

			            var label = context.index+1;//String.fromCharCode('A'.charCodeAt(0) + context.index);

			            //./images/guo.png
			            var innerHTML = MarkerList.utils.template(
			                    '<% if(data.pointType == "air") { %>' +
			                    '<div class="poi-imgbox">' +
			                    '    <span class="poi-img" style="background-image:url(./images/air.png)"></span>' +
			                    '</div>' +
			                    '<% } %>' +
			                    '<% if(data.pointType == "water") { %>' +
			                    '<div class="poi-imgbox">' +
			                    '    <span class="poi-img" style="background-image:url(./images/water.png)"></span>' +
			                    '</div>' +
			                    '<% } %>' +
			                    '<div class="poi-info-left">' +
			                    '    <h3 class="poi-title">' +
			                    '        <%- label %>. <%- data.pointname %>' +
			                    '    </h3>' +
			                    '    <div class="poi-info">' +
			                    '        <p class="poi-addr">排口编号：<%- data.pointcode %></p>' +
			                    '        <p class="poi-addr">企业：<%- data.entername %></p>' +
			                    '    </div>' +
			                    '</div>' +
			                    '<div class="clear"></div>', {
			                        data: data,
			                        label: label
			                    });

			            if (recycledListElement) {
			                recycledListElement.innerHTML = innerHTML;
			                return recycledListElement;
			            }

			            return '<li class="poibox">' +
			                innerHTML +
			                '</li>';
			        },
			        //列表节点上监听的事件
			        listElementEvents: ['click', 'mouseenter', 'mouseleave'],
			        //marker上监听的事件
			        markerEvents: ['click', 'mouseover', 'mouseout'],
			        //makeSelectedEvents:false,
			        selectedClassNames: 'selected',
			        autoSetFitView: true
			    });

			    pointML.markerList = markerList;

			    pointML.goPage(1);

			    markerList.on('selectedChanged', function(event, info) {

			        if (info.selected) {

			            console.log(info);
			            
			            if(info.selected.data) {
			            	var param = {
			            		pointcode:info.selected.data.pointcode,
			            		pointname:info.selected.data.pointname,
			            		pointType:info.selected.data.pointType
			            	};
			            	pointML.openPointDetailWin(param);
			            }
			            
			            if (info.selected.marker) {
			                //更新为选中样式
			                info.selected.marker.setIconStyle(selectedIconStyle);
			            }

			            //选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
			            if (!info.sourceEventInfo.isListElementEvent) {

			                if (info.selected.listElement) {
			                    scrollListElementIntoView($(info.selected.listElement));
			                }
			            }
			        }

			        if (info.unSelected && info.unSelected.marker) {
			            //更新为默认样式
			            info.unSelected.marker.setIconStyle(defaultIconStyle);
			        }
			    });

			    markerList.on('listElementMouseenter markerMouseover', function(event, record) {

			        if (record && record.marker) {

			            forcusMarker(record.marker);

			            //this.openInfoWindowOnRecord(record);

			            //非选中的id
			            if (!this.isSelectedDataId(record.id)) {
			                //设置为hover样式
			                record.marker.setIconStyle(hoverIconStyle);
			                //this.closeInfoWindow();
			            }
			        }
			    });

			    markerList.on('listElementMouseleave markerMouseout', function(event, record) {

			        if (record && record.marker) {

			            if (!this.isSelectedDataId(record.id)) {
			                //恢复默认样式
			                record.marker.setIconStyle(defaultIconStyle);
			            }
			        }
			    });

			    //数据输出完成
			    markerList.on('renderComplete', function(event, records) {

			    });

			    // markerList.on('*', function(type, event, res) {
			    //     console.log(type, event, res);
			    // });

			    function forcusMarker(marker) {
			        marker.setTop(true);

			        //不在地图视野内
			        if (!(gis.map.getBounds().contains(marker.getPosition()))) {

			            //移动到中心
			        	gis.map.setCenter(marker.getPosition());
			        }
			    }

			    function isElementInViewport(el) {
			        var rect = el.getBoundingClientRect();

			        return (
			            rect.top >= 0 &&
			            rect.left >= 0 &&
			            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
			            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
			        );
			    }

			    function scrollListElementIntoView($listEle) {

			        if (!isElementInViewport($listEle.get(0))) {
			            $('#panel').scrollTop(($listEle.offset().top - $listEle.parent().offset().top)+'px');
			            //console.log($listEle.offset().top - $listEle.parent().offset().top);
			        }

			        //闪动一下
			        $listEle
			            .one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
			                function(e) {
			                    $(this).removeClass('flash animated');
			                }).addClass('flash animated');
			    }
			});
		},
		
		/**
		 * 销毁分页后从第一页开始渲染MarkerList
		 */
		reRenderData:function(data){
			pointML.inited = false;
			pointML.$pagination.twbsPagination('destroy');
			pointML.goPage(1);
		},
		
		/**
		 * 清空MarkerList数据，以及销毁分页
		 */
		clearData: function(){
			pointML.inited = false;
			pointML.$pagination.twbsPagination('destroy');
			if(pointML.markerList && pointML.markerList.getData() && pointML.markerList.getData().length>0) {
				pointML.markerList.clearData();
			}
			if($('#pointTotal').length>0) {
				$('#totalPointContent').html("");
			}
		},
		
		/**
		 * 排污口废气废水数量汇总
		 */
		renderTotal:function(data){
			AMapUI.loadUI(['misc/MarkerList'], function(MarkerList) {
				var totalList = '<ul id="pointTotal">'+
									'<li>'+
									'<div class="n-icon01 icon-list on"><span>废气：<a href="#">'+data.airpointquantity+'</a></span></div>'+
									'</li>'+
									'<li>'+
										'<div class="n-icon02 icon-list on"><span>废水：<a href="#">'+data.waterpointquantity+'</a></span></div>'+
									'</li>'+
								'</ul>';
				var html = MarkerList.utils.template(totalList, {data: data});  
				$("#totalPointContent").html("").html(html); 
			});
		},
		
		/**
		 * 打开窗口查看排口信息
		 */
		openPointDetailWin: function(param){
			pointDetailCard.loadJsonData(param);
		}
	};
	
	return pointML;
});